import pygame, sys
from pygame.locals import *

from dnoteat import player, food

pygame.init()
pygame.mixer.init()
pygame.mouse.set_visible(False)  # 鼠标消失不见
bg_size = width, height = 1200, 800

screen = pygame.display.set_mode(bg_size)
pygame.display.set_caption("螃蟹🦀和乌龟🐢")

# 背景图片
background = pygame.image.load('../images/terr.jpeg').convert_alpha()
# 设置字体声音图片
score_font = pygame.font.Font('../fengheguai.otf', 30)  # 48 字体大小
title_font = pygame.font.Font('../fengheguai.otf',45)
# 常量
TEXTCOLOR = (0, 0, 0)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
WHITE = (255, 255, 255)
BAGCOLOR = (255, 255, 255)


# 终止和暂停游戏
def terminate():
    pygame.quit()
    sys.exit()


# 食物添加函数
def add_food1(group1, group2, num):
    for i in range(num):
        food1 = food.food1(bg_size)
        group1.add(food1)
        group2.add(food1)


# 食物添加函数
def add_food2(group1, group2, num):
    for i in range(num):
        food2 = food.food2(bg_size)
        group1.add(food2)
        group2.add(food2)






def drawArc(surf, color, center, radius, width, end_angle):
    arc_rect = pygame.Rect(0, 0, radius * 2, radius * 2)
    arc_rect.center = center
    pygame.draw.arc(surf, color, arc_rect, 0, end_angle, width)


# 文本渲染函数
def drawText(text, font, surface, x, y, textcolor):
    textobj = font.render(text, 1, textcolor)
    textrect = textobj.get_rect()
    textrect.topleft = (x, y)
    surface.blit(textobj, textrect)

def waitForPlayerToPressKey():
    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                terminate()
            if event.type == KEYDOWN:
                if event.key == K_ESCAPE:  # Pressing ESC quits.
                    terminate()
                elif event.key == K_1:
                    return 1
                elif event.key == K_2:
                    return 2
                elif event.key == K_3:
                    return 3

pygame.mixer.music.load('../sounds/game2bg.mp3')
pygame.mixer.music.set_volume(0.2)

eat_sound = pygame.mixer.Sound('../sounds/button.mp3')
eat_sound.set_volume(0.7)
get_sound = pygame.mixer.Sound('../sounds/getSound.mp3')
get_sound.set_volume(0.7)
victory_sound = pygame.mixer.Sound('../sounds/victory.mp3')
victory_sound.set_volume(0.2)
# 循环 开始游戏

def main():
    # 开始游戏
    screen.fill(WHITE)
    drawText('乌龟和螃蟹', title_font, screen, (width / 9), (height / 3), BLACK)
    drawText('按1  2  3 键分别游玩10s  20s  30s', title_font, screen, (width / 9), (height / 3) + 60, BLACK)
    pygame.display.update()

    # 游戏开始页面
    timeLevel = waitForPlayerToPressKey()

    pygame.mixer.music.play(-1)
    clock = pygame.time.Clock()
    pygame.display.update()
    # 乌龟 分数
    wugui_score = 0

    # 螃蟹 分数
    pangxie_score = 0

    # 延迟变量
    delay = 100
    # 中弹图片索引
    e1_destory_index = 0
    e2_destory_index = 0
    e3_destory_index = 0
    my_destory_index = 0

    # 生成乌龟
    wugui = player.player1(bg_size)

    # 生成螃蟹
    pangxie = player.player2(bg_size)

    # 绘制食物
    foods = pygame.sprite.Group()
    pangxie_foods = pygame.sprite.Group()
    wugui_foods = pygame.sprite.Group()

    add_food1(wugui_foods, foods, 40)
    add_food2(pangxie_foods, foods, 40)





    # 倒计时
    timer_event = pygame.USEREVENT + 1
    pygame.time.set_timer(timer_event, 1000)
    font = pygame.font.SysFont(None, 100)
    counter = 10*timeLevel
    text = font.render(str(counter), True, (0, 128, 0))

    running = True
    while running:
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == KEYDOWN:
                if event.key == K_ESCAPE:
                    pygame.quit()
                    sys.exit()
            elif event.type == timer_event:
                counter -= 1
                text = font.render(str(counter), True, (0, 128, 0))
                if counter == 0:
                    pygame.time.set_timer(timer_event, 0)

        screen.fill(BAGCOLOR)
        # 倒计时绘制
        text_rect = text.get_rect(center=screen.get_rect().center)
        screen.blit(text, text_rect)
        # drawArc(screen, (255, 0, 0), (100, 100), 90, 10, 2 * math.pi * counter / 100)

        if counter:  # 绘制wugui

            key_pressed = pygame.key.get_pressed()
            if key_pressed[K_w]:
                wugui.moveUp()
            if key_pressed[K_s]:
                wugui.moveDown()
            if key_pressed[K_a]:
                wugui.moveLeft()
            if key_pressed[K_d]:
                wugui.moveRight()
            if key_pressed[K_UP]:
                pangxie.moveUp()
            if key_pressed[K_DOWN]:
                pangxie.moveDown()
            if key_pressed[K_LEFT]:
                pangxie.moveLeft()
            if key_pressed[K_RIGHT]:
                pangxie.moveRight()

            if wugui.active:

                screen.blit(wugui.image1, wugui.rect)
            else:
                # 毁灭
                if not (delay % 3):
                    wugui.reset()
            # 绘制pangxie
            if pangxie.active:

                screen.blit(pangxie.image1, pangxie.rect)
            else:
                # 毁灭
                if not (delay % 3):
                    wugui.reset()
            # 绘制乌龟食物
            for each in wugui_foods:
                if each.active:
                    # each.move()
                    screen.blit(each.image, each.rect)
                else:

                    each.reset()

            # 绘制螃蟹食物
            for each in pangxie_foods:
                if each.active:
                    # each.move()
                    screen.blit(each.image, each.rect)
                else:
                    each.reset()
            # 碰撞检测
            # 检测是否被撞
            wugui_foods_down = pygame.sprite.spritecollide(wugui, foods, False, pygame.sprite.collide_mask)
            pangxie_foods_down = pygame.sprite.spritecollide(pangxie, foods, False, pygame.sprite.collide_mask)
            wugui_wugui_foods_down = pygame.sprite.spritecollide(wugui, wugui_foods, False,
                                                                 pygame.sprite.collide_mask)
            wugui_pangxie_foods_down = pygame.sprite.spritecollide(wugui, pangxie_foods, False,
                                                                   pygame.sprite.collide_mask)
            pangxie_pangxie_foods_down = pygame.sprite.spritecollide(pangxie, pangxie_foods, False,
                                                                     pygame.sprite.collide_mask)
            pangxie_wugui_foods_down = pygame.sprite.spritecollide(pangxie, wugui_foods, False,
                                                                   pygame.sprite.collide_mask)

            if pangxie_foods_down:
                eat_sound.play()
                if pangxie_pangxie_foods_down:
                    pangxie_score += 1
                    for e in pangxie_pangxie_foods_down:
                        e.active = False
                if pangxie_wugui_foods_down:
                    pangxie_score -= 1
                    for e in pangxie_wugui_foods_down:
                        e.active = False

            if wugui_foods_down:
                get_sound.play()
                if wugui_wugui_foods_down:
                    wugui_score += 1
                    for e in wugui_wugui_foods_down:
                        e.active = False
                if wugui_pangxie_foods_down:
                    wugui_score -= 1
                    for e in wugui_pangxie_foods_down:
                        e.active = False
            # 检测 两个玩家是否碰撞
            is_col = pygame.sprite.collide_mask(pangxie, wugui)



        elif counter == 0:

            # 背景音乐停止
            pygame.mixer.music.stop()
            #pygame.time.wait(1 * 1000)
            victory_sound.play(fade_ms=900)
            # 结束页面渲染
            screen.fill(BAGCOLOR)
            over_txt = title_font.render("按任意键重玩", True, BLACK)
            if wugui_score > pangxie_score:
                drawText('玩家一胜利!', title_font, screen, (width / 3), (height / 3), BLACK)
                screen.blit(wugui.image1, ((width / 3) - 60, (height / 3) - 10))
                victory_sound.play()
            elif wugui_score < pangxie_score:
                drawText('玩家二胜利!', title_font, screen, (width / 3), (height / 3), BLACK)
                screen.blit(pangxie.image1, ((width / 3) - 60, (height / 3) - 10))
            elif wugui_score == pangxie_score:
                drawText('玩家一&玩家二胜利!', title_font, screen, (width / 3), (height / 3), BLACK)
                screen.blit(pangxie.image1, ((width / 3) - 60, (height / 3) - 10))
                screen.blit(wugui.image1, ((width / 3) - 60, (height / 3) + 50))

            screen.blit(over_txt, [400, 400])
            pygame.display.update()
            # 重新开始游戏
            while True:
                for event in pygame.event.get():
                    if event.type == QUIT:
                        terminate()
                    if event.type == KEYDOWN:
                        if event.key == K_ESCAPE:  # Pressing ESC quits.
                            terminate()
                        elif event.key == K_SPACE:
                            main()

        # 分数绘制
        wugui_score_str = score_font.render("玩家一分数为：" + str(wugui_score), True, BLACK)
        screen.blit(wugui_score_str, [15, 5])
        pangxie_score_str = score_font.render("玩家二分数为：" + str(pangxie_score), True, BLACK)
        screen.blit(pangxie_score_str, [900, 5])

        # 延迟参数
        if not (delay % 5):
            # switch_image = not switch_image
            pass
        delay -= 1
        if not delay:
            delay = 100

        pygame.display.flip()
        clock.tick(60)


if __name__ == '__main__':
    main()
